<html>
<head>

<title>Groovy Goodness: the as Keyword</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: the as Keyword</h3>

<div class="post">
<p>We can change the type of objects with the <code>as</code> keyword in Groovy. We can even make maps and closure look like interface implementations when we use <code>as</code>. Furthermore we can use <code>as</code> to create an alias for an import statement.</p>
<pre class="brush:groovy">
import java.text.MessageFormat as mf // Alias mf

// Use alias and use as to convert list to Object[]:
assert 'Simple message!' == mf.format('Simple {0}!', ['message'] as Object[])

// Normal Groovy list:
def intList = [1,2,3,4]
assert 'java.util.ArrayList' == intList.class.name
assert 4 == intList.size()

// Coerse to int[]:
def intArray = intList as int[]
assert 'java.util.ArrayList' != intArray.class.name
assert 4 == intArray.length  // Use int[] property.

// Use as to create Date object from list:
def date = [109, 8, 6] as Date
assert 2009 == date[Calendar.YEAR]
assert 8 == date[Calendar.MONTH]
assert 6 == date[Calendar.DATE]

// Use as to treat closure as implementation for
// the Runnable interface:
def t = new Thread({ println 'hello' } as Runnable)
t.start()  // Output: hello

// Use as to treat map as implementation for
// the Runnable interface:
def t2 = new Thread([run: { println 'hello' }] as Runnable)
t2.start()  // Output: hello
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>